<template>
  <div class="app-container">
    <YearMonthSelector v-model="queryParams.reportingYearMonth" @change="handleYearMonthChange" />

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标识" prop="identifier">
        <el-input
          v-model="queryParams.identifier"
          placeholder="请输入标识"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑物名称" prop="buildingName">
        <el-input
          v-model="queryParams.buildingName"
          placeholder="请输入建筑物名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑物编号" prop="buildingCode">
        <el-input
          v-model="queryParams.buildingCode"
          placeholder="请输入建筑物编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属街路巷" prop="streetAlley">
        <el-input
          v-model="queryParams.streetAlley"
          placeholder="请输入所属街路巷"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼层数" prop="floorCount">
        <el-input
          v-model="queryParams.floorCount"
          placeholder="请输入楼层数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑物结构" prop="buildingStructure">
        <el-input
          v-model="queryParams.buildingStructure"
          placeholder="请输入建筑物结构"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['report:standard_building:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['report:standard_building:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['report:standard_building:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['report:standard_building:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          @click="handleReport"
        >立即上报</el-button>
      </el-col>
      <el-col :span="1.5" v-else>
        <el-button
          type="info"
          plain
          disabled
        >已上报</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="standard_buildingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="标识" align="center" prop="identifier" />
      <el-table-column label="建筑物名称" align="center" prop="buildingName" />
      <el-table-column label="建筑物编号" align="center" prop="buildingCode" />
      <el-table-column label="所属街路巷" align="center" prop="streetAlley" />
      <el-table-column label="楼层数" align="center" prop="floorCount" />
      <el-table-column label="建筑物结构" align="center" prop="buildingStructure" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="reportStatus === '0'">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['report:standard_building:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['report:standard_building:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标准建筑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="standard_buildingRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标识" prop="identifier">
          <el-input v-model="form.identifier" placeholder="请输入标识" />
        </el-form-item>
        <el-form-item label="建筑物名称" prop="buildingName">
          <el-input v-model="form.buildingName" placeholder="请输入建筑物名称" />
        </el-form-item>
        <el-form-item label="建筑物编号" prop="buildingCode">
          <el-input v-model="form.buildingCode" placeholder="请输入建筑物编号" />
        </el-form-item>
        <el-form-item label="所属街路巷" prop="streetAlley">
          <el-input v-model="form.streetAlley" placeholder="请输入所属街路巷" />
        </el-form-item>
        <el-form-item label="楼层数" prop="floorCount">
          <el-input v-model="form.floorCount" placeholder="请输入楼层数" />
        </el-form-item>
        <el-form-item label="建筑物结构" prop="buildingStructure">
          <el-input v-model="form.buildingStructure" placeholder="请输入建筑物结构" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Standard_building">
import { listStandard_building, getStandard_building, delStandard_building, addStandard_building, updateStandard_building } from "@/api/report/standard_building"
import { getMonthlyReportStatusDetail, addReportRecord } from "@/api/report/monthlyReportStatus"
import YearMonthSelector from "@/components/YearMonthSelector/index.vue";

const { proxy } = getCurrentInstance()

const standard_buildingList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const reportStatus = ref("0") // 默认未上报

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    identifier: null,
    buildingName: null,
    buildingCode: null,
    streetAlley: null,
    floorCount: null,
    buildingStructure: null,
    reportingYearMonth: null
  },
  rules: {
    identifier: [
      { required: true, message: "标识不能为空", trigger: "blur" }
    ],
    buildingName: [
      { required: true, message: "建筑物名称不能为空", trigger: "blur" }
    ],
    buildingCode: [
      { required: true, message: "建筑物编号不能为空", trigger: "blur" }
    ],
    streetAlley: [
      { required: true, message: "所属街路巷不能为空", trigger: "blur" }
    ],
    floorCount: [
      { required: true, message: "楼层数不能为空", trigger: "blur" }
    ],
    buildingStructure: [
      { required: true, message: "建筑物结构不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询标准建筑列表 */
function getList() {
  loading.value = true
  // 确保携带 reportingYearMonth 参数
  if (!queryParams.value.reportingYearMonth) {
    const now = new Date()
    queryParams.value.reportingYearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  }

  // 获取上报状态
  getReportStatus()

  listStandard_building(queryParams.value).then(response => {
    standard_buildingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 获取上报状态
function getReportStatus() {
  const tableName = "standard_building"
  const reportYearMonth = queryParams.value.reportingYearMonth
  if (reportYearMonth) {
    getMonthlyReportStatusDetail(tableName, reportYearMonth).then(response => {
      reportStatus.value = response.data.isReported
    }).catch(() => {
      // 如果获取失败，默认为未上报
      reportStatus.value = "0"
    })
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    identifier: null,
    buildingName: null,
    buildingCode: null,
    streetAlley: null,
    floorCount: null,
    buildingStructure: null,
    reportingYearMonth: queryParams.value.reportingYearMonth
  }
  proxy.resetForm("standard_buildingRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加标准建筑"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getStandard_building(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改标准建筑"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["standard_buildingRef"].validate(valid => {
    if (valid) {
      // 确保传递 reportingYearMonth 字段
      form.value.reportingYearMonth = queryParams.value.reportingYearMonth;
      if (form.value.id != null) {
        updateStandard_building(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStandard_building(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除标准建筑编号为"' + _ids + '"的数据项？').then(function() {
    return delStandard_building(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('report/standard_building/export', {
    ...queryParams.value
  }, `standard_building_${new Date().getTime()}.xlsx`)
}

/** 上报按钮操作 */
function handleReport() {
  proxy.$modal.confirm('确定要上报数据吗？上报后数据将不可修改！').then(() => {
    const reportData = {
      tableName: "standard_building",
      reportYearMonth: queryParams.value.reportingYearMonth
    }

    return addReportRecord(reportData)
  }).then(response => {
    if (response.data === 1) {
      proxy.$modal.msgSuccess("上报成功")
      // 更新上报状态为已上报
      reportStatus.value = "1"
    } else {
      proxy.$modal.msgError("上报失败")
    }
  }).catch(error => {
    if (error !== 'cancel') {
      proxy.$modal.msgError("上报失败: " + error.message)
    }
  })
}

// 年月选择变化处理
function handleYearMonthChange() {
  getList()
}

getList()
</script>
